import React, { Component } from 'react'
import { Form, Icon, Input, Button, Modal } from 'antd'
import { connect } from 'react-redux'
import { withRouter, Link } from 'react-router-dom'
import { bindActionCreators } from 'redux'
import * as restCallActions from '../../../actions/rest-action'

const FormItem = Form.Item

@connect(
	state => {
		let getUserProfileState = state.restReducer.toJS()['CREATE_USER']
		let isUserExist = state.restReducer.toJS()['IS_USER_EXIST']
		return ({
			isSuccess: getUserProfileState.isSuccess,
			isFailed: getUserProfileState.isFailed,
			response: getUserProfileState.response,
			isUserExist: isUserExist.response,
		})
	},
	dispatch => ({
		restCallActions: bindActionCreators({...restCallActions}, dispatch)
	})
)
class RegistrationForm extends Component {
	constructor(props) {
		super(props)
		this.state = {
			confirmDirty: false,
			showErr: false,
			isUserExist: false,
		}
	}

	componentWillReceiveProps(nextProps) {
		let { isSuccess, isFailed, response, isUserExist } = nextProps
		this.setState({
			isUserExist: isUserExist=='true',
		})
		if(isSuccess) {
			Modal.success({
				title: 'User has been created successful.',
				onOk: () => {
					this.props.restCallActions.restClearAction('CREATE_USER'),
					this.props.history.push('login')
				}
			})
		}
		if(isFailed) {
			Modal.error({
				title: 'Occurred exception.',
				content: response.errorMessage,
				onOk: this.clearMsg,
			})
		}
	}

	clearMsg = () => {
		this.props.restCallActions.restClearAction('CREATE_USER')
		this.setState({
			showErr: false,
		})
	}

	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			if (!err && !!!this.state.isUserExist) {
				let user = {
					userId: values.userId,
					userName: values.userName,
					password: values.password,
					email: values.email,
				}
				this.props.restCallActions.restCallAction('CREATE_USER','http://localhost:8848/vtg/user', 'POST', user, true)
			}
		})
	}

	checkUserExist = (e) => {
		const userId = e.target.value
		if(!!userId) {
			this.props.restCallActions.restCallAction('IS_USER_EXIST', `http://localhost:8848/vtg/user/isExist/${userId}`, 'GET', null, true)
		}
	}

	handleConfirmBlur = (e) => {
		const value = e.target.value
		this.setState({ confirmDirty: this.state.confirmDirty || !!value });
	}

	compareToFirstPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && value !== form.getFieldValue('password')) {
			callback('Two passwords that you enter is inconsistent.');
		} else {
			callback();
		}
	}

	validateToNextPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && this.state.confirmDirty) {
			form.validateFields(['confirm'], { force: true });
		}
		callback();
	}

	render() {
		const { getFieldDecorator } = this.props.form
		const { isUserExist } = this.state
		const formItemLayout = {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 8 },
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 10 },
			},
		}
		const tailFormItemLayout = {
			wrapperCol: {
				xs: {
					span: 24,
					offset: 0,
				},
				sm: {
					span: 16,
					offset: 8,
				},
			},
		}

		return (
			<Form onSubmit={this.handleSubmit}>
				<FormItem
					{...formItemLayout}
					label="User id"
				>
					{getFieldDecorator('userId', {
						rules: [{ required: true, message: 'Please input your user id.' }],
					})(
						<Input onBlur={this.checkUserExist}/>
					)}
					{isUserExist ? <font color='red'>This user id has been used, please change other one.</font> : null}
				</FormItem>
				<FormItem
					{...formItemLayout}
					label="User name"
				>
					{getFieldDecorator('userName', {
						rules: [{ required: true, message: 'Please input your user name.' }],
					})(
						<Input />
					)}
				</FormItem>
				<FormItem
					{...formItemLayout}
					label="Password"
				>
					{getFieldDecorator('password', {
						rules: [{
								required: true,
								message: 'Please input your password.'
						}, {
								validator: this.validateToNextPassword,
							}],
					})(
						<Input type="password" />
					)}
				</FormItem>
				<FormItem
					{...formItemLayout}
					label="Confirm Password"
				>
					{getFieldDecorator('confirm', {
						rules: [{
							required: true, message: 'Please confirm your password.',
						}, {
							validator: this.compareToFirstPassword,
						}],
					})(
						<Input type="password" onBlur={this.handleConfirmBlur} />
					)}
				</FormItem>
				<FormItem
					{...formItemLayout}
					label="E-mail"
				>
					{getFieldDecorator('email', {
						rules: [{
							type: 'email', message: 'The input is not valid E-mail.',
						}, {
							required: true, message: 'Please input your E-mail.',
						}],
					})(
						<Input />
					)}
				</FormItem>
				<FormItem {...tailFormItemLayout}>
					<Button type="primary" htmlType="submit">Register</Button>
					<Button style={{ marginLeft: 18 }}>
						<Icon type="left" />
						<Link to="/login">
							Back to login
						</Link>
					</Button>
				</FormItem>
			</Form>
		)
	}
}

export default withRouter(Form.create()(RegistrationForm))